require('../engine/jsb-http');
// function getStringOfObject(obj) {
//     var ret = '';
//     for (var k in obj)
//     {
//         ret += (k + '=' + obj[k] + ', ');
//     }
//     return ret;
// }

jsb.sendMessageToApp = function(type, msgObj, tag) {
    if (!type) {
        console.error('jsb.sendMessageToApp, type is empty!');
        return;
    }
    msgObj = msgObj || {};
    tag = tag || 0;
    jsb._sendMessageToApp(type, msgObj, tag);
};

jsb.sendMessageToAppSync = function(type, msgObj, tag) {
    if (!type) {
        console.error('jsb.sendMessageToAppSync, type is empty!');
        return null;
    }
    msgObj = msgObj || {};
    tag = tag || 0;
    return jsb._sendMessageToAppSync(type, msgObj, tag);
};

jsb.onReceiveMessageFromApp = function(type, msgObj, tag) {
    console.log("onReceiveMessageFromApp: " + type);
    var event = new Event('onReceiveMessageFromApp');
    event.appMsgObj = {
        type: type,
        msgObj: msgObj,
        tag: tag
    };
    window.dispatchEvent(event);
    // console.log('onReceiveMessageFromApp: ' + type + ', msg: ' + getStringOfObject(msgObj) + ', tag: ' + tag);
    // console.log('onReceiveMessageFromApp: bin: ' + msgObj.bin.byteLength);
    // var arr = new Uint8Array(msgObj.bin);
    // for (var i = 0; i < arr.length; ++i) {
    //     console.log('bin[' + i + ']=' + arr[i]);
    // }

    // setTimeout(function(){
    //     jsb.sendMessageToApp("xxx hello", {
    //         aaa: 123,
    //         bb: "hello",
    //         cc: new Uint8Array([1,2, 34,4]),
    //         ddd: true,
    //         eee: 3203.012,
    //         fff: null,
    //         ggg: undefined,
    //         subObj: {
    //             subcc: new Uint8Array([10,20, 34, 43]),
    //             subddd: false,
    //             subeee: 123.2344,
    //         }
    //     }, 100);
    // }, 2000);

    // setTimeout(function(){
    //     var ret = jsb.sendMessageToAppSync("22xxx hello", {
    //         aaa: 1233,
    //         bb: "hello2",
    //         cc: new Uint8Array([13,12, 34,4]),
    //         ddd: false,
    //         eee: 32031.012,
    //         fff: null,
    //         ggg: undefined,
    //         subObj: {
    //             subcc: new Uint8Array([103,201, 32, 13]),
    //             subddd: false,
    //             subeee: 123.3344,
    //         }
    //     }, 100);
    //     console.log("jsb.sendMessageToAppSync returns: " + ret);
    // }, 4000);
};

// return errorMsg, null means success.
function __parseIndexHTMLContent(doc) {
    let errorMsg = null;

    let divElements = doc.getElementsByTagName('div');
    let divElementCount = divElements.length;
    if (divElementCount > 0)
    {
        let item;
        for (let i = 0; i < divElementCount; ++i) {
            let element = divElements[i];
            let attributeCount = element.attributes.length;
            if (attributeCount > 0) {
                item = element.attributes.getNamedItem('class');
                if (item && item.nodeValue === 'egret-player') {
                    console.log('Found egret-player...');

                    let egretEntryElement = new HTMLDivElement();
                    for (let j = 0; j < attributeCount; ++j)
                    {
                        item = element.attributes[j];
                        egretEntryElement.setAttribute(item.nodeName, item.nodeValue);
                    }

                    window._egretEntryElement = egretEntryElement;
                }
            }
        }
    }

    let scripts = doc.getElementsByTagName('script');
    let len = scripts.length;
    if (len > 0) {
        let item;
        for (let i = 0; i < len; ++i) {
            let script = scripts[i];
            if (script.attributes.length > 0 && (item = script.attributes.getNamedItem('src'))) {
                let url = item.nodeValue;
                if (url) {
                    let urlLowercase = url.toLowerCase();
                    if (urlLowercase.indexOf('http://') !== 0 && urlLowercase.indexOf('https://') !== 0) {
                        require(url);
                    }
                    else {
                        console.error("Could not support to load remote script (" + url + ") in index.html on YY runtime!");
                    }
                }
            }
            else {
                if (script.firstChild && script.firstChild.data) {
                    jsb.evalString(script.firstChild.data);
                }
            }
        }
    }
    else {
        errorMsg = 'Parse index.html failed, no scripts!';
    }

    return errorMsg;
}

function parseIndexHTMLContent(indexHtml) {
    let parser = new DOMParser();
    let doc = parser.parseFromString(indexHtml, 'text/html');
    __parseIndexHTMLContent(doc);
}

window.__getLocationEntryURL = function(){
    return window.location.protocol+"//"+window.location.host+"entry/";
}

window.__getLocationURL = function(){
    return window.location.protocol+"//"+window.location.host;
}

window.getNextScript = function(scripts, httpRequest, doc){
    if(!scripts) {
        jsb._notifyStartGameFailure('Could not find script html!');
        return;
    }
    var t = scripts.pop();
    if(t){
        var url = window.__getLocationURL()+t;
        httpRequest.send(url,'string',"get");
        return url;
    }
    else{
        window.__initWithIndexHTML(doc);
    }
}

window.loadIndexScripts = function(indexHtml){
    if(!indexHtml) {
        jsb._notifyStartGameFailure('Could not find index.html!');
        return;
    }
    let parser = new DOMParser();
    var doc;
    var errorMsg;
    try {
        doc = parser.parseFromString(indexHtml, 'text/html');
        if(!doc)
        {
            errorMsg = 'Could not parseFromString with index.html';
        }
    } catch (e) {
        errorMsg = e.toString();
    }
    if (errorMsg) {
        jsb._notifyStartGameFailure(errorMsg);
        return;
    }


    let scripts = doc.getElementsByTagName('script'); 
    let temp = [];
    var item;
    for (let i = 0; i < scripts.length; ++i)
    {
        var script = scripts[i];
        if (script.attributes.length > 0 && (item = script.attributes.getNamedItem('src'))) {
            temp.push(item.nodeValue);
        }          
    }
    temp.reverse();
    jsbLoadScripts(temp, doc);
}

window.jsbLoadScripts = function (temp, doc, url) {
    var index = new jsb.HttpRequest();
    index.timeout = 60000;
    index.on('complete', window, window.getNextScript, [temp, index, doc]);

    if (url) {
        index.on('error', window, window.requestScript, [temp, doc, url]);
        index.send(url, 'string', "get");
    } else {
        var url = window.getNextScript(temp, index, doc);
        index.on('error', window, window.jsbLoadScripts, [temp, doc, url]);
    }
};

window._initWithIndexHTML = function() {
    var index = new jsb.HttpRequest();
    index.on('complete', window, window.loadIndexScripts);
    index.on('error', window, window._initWithIndexHTML);
    index.send(window.__getLocationEntryURL()+window.location.href+'?'+(new Date().getTime()),'string',"get");
}

window.__initWithIndexHTML = function(doc) {
    var errorMsg = null;
    // var indexHtml = jsb.fileUtils.getStringFromFile('index.html');
    try {
        errorMsg = __parseIndexHTMLContent(doc);
    } catch (e) {
        errorMsg = e.toString();
    }

    if (errorMsg) {
        jsb._notifyStartGameFailure(errorMsg);
    }

//FIXME:cjh: H5 engine and some 3rd SDK need 'eval' & 'new Function', so currently, we need to enable it by default.
    // Disable eval and new Function
    // delete window.eval;
// (function() {
//     var oldFunction = Function;
//     window.Function = function(a) {
//         throw new Error("new Function is forbidden!");
//     };

//     Function.prototype = oldFunction.prototype;
// })();
};
